import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Login from '@/views/login';
import store from '@/store/index';
import ajax from '@/utils/ajax';
import { formartMenu } from "@/utils/initMenus";
import Test from "../views/moment/test.vue"


Vue.use(VueRouter);

const routes = [
  {
    path:'/login',
    component:Login,
  },
  {
    path:'/',
    component:Home,
  },
  {
    path:'/test',
    component:Test
  }
];

const router = new VueRouter({
  routes,
});

/**
 * to 将要去那个页面
 * from 从哪个页面来
 * next 放行到哪个页面
 */

router.beforeEach((to,from,next) => {
  //判断是否登录
  const token = sessionStorage.getItem("token");
  if (!token){
    if (to.path === '/login'){
      next();
    }else {
      next(`/login?redirect = ${to.fullPath}`);
    }

  }else{
    //向后端发送请求
      ajax.get('/user/getInfo').then((res) => {

        const user = res.data.data;
        store.commit('setName',user.username)
        store.commit('setAvatar',user.avatar)

        if (user.roles.length > 0){
          //添加角色，菜单，权限等信息
          store.commit('setRoles', user.roles);
          //格式化菜单
          const menuList = formartMenu(user.menus);
          for(let i = 0, length = menuList.length; i< length; i+=1){
            const element = menuList[i];
            router.addRoute(element);
          }
          store.commit('setMenus', menuList);
          store.commit('setPermissions', user.permissions);
         }
      });

    //已经登录
    if (to.path === '/login'){
       next('/');
    }else {
        next();
    }


  }
});

export default router;
